from django.shortcuts import render,redirect
from myapp.models import *
from django.db.models import Q
from django.http import HttpResponse,JsonResponse
# Create your views here.

def index(request):
    return render(request,'myapp/index.html')


def login(request):
    if request.session.has_key('is_login'):
        username = request.session['username']
        return redirect('/content')
    if 'username' in  request.COOKIES:
        username = request.COOKIES['username']
    else:
        username=''

    return render(request,'myapp/login.html',{'username':username})

def login_check(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    save_user = request.POST.get('save_user')
    auto_login = request.POST.get('auto_login')
    try:
        user = Userinfo.objects.get(Q(username=username),Q(password=password))
        reposon = redirect('/content',{'username':username})
        if save_user == 'on':
            reposon.set_cookie('username',username,max_age=12*24*3600)

        if auto_login == 'on':
            request.session['username'] = username
            request.session['is_login'] = True

        print(save_user)
        print(auto_login)
        return reposon

    except:
        return HttpResponse('账号或密码不正确')

def content(request):

    return render(request,'myapp/content.html')




def clear(request):
    request.session.clear()
    request.session.flush()

    request.COOKIES.clear()
    return JsonResponse({'nub':0})


def newuser(request):
    return render(request,'myapp/newuser.html')



def reg_user(request):
    username = request.GET.get('username')
    password = request.GET.get('password')
    nub = Userinfo()
    nub.username = username
    nub.password = password
    nub.save()
    return redirect('/new_success')

def new_success(request):
    return render(request,'myapp/new_success.html')


def test(request):
    pass

